<template>
  <!-- // 分配角色 -->
  <div>
    <el-checkbox-group
      v-model="roleIds"
    >
      <el-checkbox
        v-for="item in list"
        :key="item.id"
        :label="item.id"
      >{{ item.name }}
      </el-checkbox>
    </el-checkbox-group>

    <div style="margin-top: 20px; text-align: right">
      <el-button type="primary" @click="hSubmit">确定</el-button>
      <el-button @click="closeDialog">取消</el-button>
    </div>
  </div>
</template>
<script>
import { getRoles } from '@/api/settings'
import { assignRoles, getUserInfoById } from '@/api/user'
export default {
  props: {
    userId: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      roleIds: [],
      list: []
    }
  },
  created() {
    this.loadRoles()
  },
  methods: {
    async  hSubmit() {
      try {
        const res = await assignRoles({ id: this.userId, roleIds: this.roleIds })
        console.log('assignRoles', res)
        // 保存数据
        this.$emit('success')
      } catch (err) {
        console.log('assignRoles', err)
      }
    },
    async loadRoles() {
      // 取一个比较大的页码来一次模拟获取所有的数据
      const res = await getRoles({ page: 1, pagesize: 100 })
      // 获取用户已拥有的角色
      this.list = res.data.rows
      const roleIds = await getUserInfoById(this.userId)
      // 使用用户拥有的角色id roleIds 让表单处于选中状态
      this.roleIds = roleIds.data.roleIds || []
      console.log(this.roleIds)
    },
    closeDialog() {
      this.$emit('close')
    }
  }
}
</script>
